package com.biboheart.adapter.express.support;

import com.biboheart.adapter.express.actuator.GenericActuator;
import com.biboheart.adapter.support.exception.ConvertException;
import com.biboheart.adapter.support.utils.ObjectTypeUtils;

import java.util.HashMap;
import java.util.Map;

public class GenericActuatorService implements ConfigurableActuatorService {
    private final Actuators actuators = new Actuators();

    @Override
    public <T> T execute(Class<T> valueType, String instructName, Object source, Object... args) {
        return ObjectTypeUtils.convertType(execute(instructName, source, args), valueType);
    }

    @Override
    public Object execute(String instructName, Object source, Object... args) {
        GenericActuator actuator = actuators.getConverter(instructName);
        if (null == actuator) {
            throw new ConvertException("未找到合适的转换器");
        }
        return actuator.execute(source, args);
    }

    @Override
    public void addActuator(String name, GenericActuator actuator) {
        actuators.add(name, actuator);
    }

    @Override
    public void removeActuator(String name) {
        actuators.remove(name);
    }

    private static class Actuators {
        private final Map<String, GenericActuator> actuatorHash = new HashMap<>();

        public void add(String name, GenericActuator actuator) {
            actuatorHash.put(name, actuator);
        }

        public void remove(String name) {
            actuatorHash.remove(name);
        }

        public GenericActuator getConverter(String name) {
            if ("".equals(name) || null == name) {
                return null;
            }
            return actuatorHash.get(name);
        }
    }
}
